package com.gzbsoft.sc.modules.app.interceptor;
import cn.hutool.core.util.StrUtil;
import com.gzbsoft.sc.common.annotation.Login;
import com.gzbsoft.sc.common.config.JwtConfig;
import com.gzbsoft.sc.common.exception.RRException;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    private final JwtConfig jwtConfig;
    public static final String USER_KEY = "userId";
    public AuthorizationInterceptor(JwtConfig jwtConfig) {
        this.jwtConfig = jwtConfig;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }
        //获取用户凭证
        String token = request.getHeader(jwtConfig.getHeader());
        if (StrUtil.isBlank(token)) {
            token = request.getParameter(jwtConfig.getHeader());
        }
        //凭证为空
        if (StrUtil.isBlank(token)) {
            throw new RRException(jwtConfig.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }
        Claims claims = jwtConfig.getClaimByToken(token);
        if (claims == null || jwtConfig.isTokenExpired(claims.getExpiration())) {
            throw new RRException(jwtConfig.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }
        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));
        return true;
    }
}
